package cn.kow.kmall.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.kow.kmall.core.response.KmallResult;
import cn.kow.kmall.common.enums.KmallResultEnum;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;


/**
 * @Author: lijun
 * @Date: 2018/9/11 15:49
 */
@Slf4j
@ControllerAdvice
public class ViolationExceptionHandler {

    /**
     * 参数校验错误拦截
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = ConstraintViolationException.class)
    public Object handlerException(ConstraintViolationException ex) {
        StringBuffer sb = new StringBuffer();
        Set<ConstraintViolation<?>> violations = ex.getConstraintViolations();
        for (ConstraintViolation<?> item : violations) {
            sb.append(item.getMessage());
        }
        return KmallResult.build(KmallResultEnum.PARAM_ERROR.getCode(), KmallResultEnum.PARAM_ERROR.getMessage() + sb.toString());
    }

    /**
     * 参数校验错误拦截
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object handlerException(MethodArgumentNotValidException ex) {
        List<ObjectError> errors = ex.getBindingResult().getAllErrors();
        StringBuffer errorMsg = new StringBuffer();
        errors.stream().forEach(x -> errorMsg.append(x.getDefaultMessage()).append(";"));
        return KmallResult.build(KmallResultEnum.PARAM_ERROR.getCode(), KmallResultEnum.PARAM_ERROR.getMessage() + errorMsg.toString());
    }

}
